package top.zy.boot.async;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.zy.boot.async.service.AsyncService;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author ZackYoung
 * @version 1.0
 * @date 2021/12/18
 */
@SpringBootApplication
@RestController
@Slf4j
public class AsyncApplication {
    @Resource
    AsyncService asyncService;

    public static void main(String[] args) {
        SpringApplication.run(AsyncApplication.class, args);
    }

    @RequestMapping("/test")
    public String test() throws ExecutionException, InterruptedException {
        CompletableFuture<String> one = asyncService.asyncResult(() -> {
            long l = System.currentTimeMillis();
            System.out.println("这是第一个服务");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("共花费 {} s", (System.currentTimeMillis() - l) / 1000);
            return "";
        });
        asyncService.asyncResult(() -> {
            long l = System.currentTimeMillis();
            System.out.println("这是第2个服务");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("共花费 {} s", (System.currentTimeMillis() - l) / 1000);
        });
        CompletableFuture.allOf(one).join();
        return "完成";
    }
}
